package application.chat;

public class ChatPacket {
	private long timeStamp;
	private String name;
	private String msg;
	
	/**
	 * Makes a ChatPacket with a msg and a name as input, it also sets the timestamp
	 * @param msg The message 
	 * @param name The name of the sender of the message
	 */
	public ChatPacket(String msg, String name){
		this.msg = msg;
		this.name = name;
		this.timeStamp = System.currentTimeMillis()/1000;
		System.out.println(timeStamp);
	}


	/**
	 * Makes a chatPacket from an input string that is formatted as the protocol states
	 * @param input The input string
	 */
	public ChatPacket(String input){
		long stamp = 0;
		stamp = input.charAt(0) << 3*Constants.BYTE_LENGTH;
		stamp = stamp |input.charAt(1) << 2*Constants.BYTE_LENGTH;
		stamp = stamp |input.charAt(2) << 1*Constants.BYTE_LENGTH;
		stamp = stamp |input.charAt(3);
		this.timeStamp = stamp;
		String name = new String();
		for (int i = Constants.TIMESTAMP_BYTE_LENGTH; i < input.length() && input.charAt(i) != Constants.DELIMITER; i++){
			name += input.charAt(i);
		}
		this.name = name;
		this.msg = input.split("\07")[1];
	}
	/**
	 * Return the timeStamp of this message
	 * @return
	 */
	public long getTimeStamp(){
		return this.timeStamp;
	}
	/**
	 * Returns the message of this packet
	 * @return
	 */
	public String getMessage(){
		return this.msg;
	}
	/**
	 * Returns the name of the sender of this message
	 * @return
	 */
	public String getName(){
		return this.name;
	}
	/**
	 * Returns the content of this packet in a formatted String, this string is formatted as the protocol states
	 */
	public String toString(){
		String result =  new String();
		result += (char)((timeStamp >> 3*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)((timeStamp >> 2*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)((timeStamp >> 1*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)(timeStamp & 0x00FF);
		System.out.println(result);
		result += name;
		result += Constants.DELIMITER;
		result += msg;
		result += Constants.DELIMITER;
		return result;
	}

}
